blog

Home / DeveloperSection / Blogs / How can you dynamically add and remove form fields using JavaScript?

How can you dynamically add and remove form fields using JavaScript?

How can you dynamically add and remove form fields using JavaScript?

Ravi Vishwakarma 721 17-Jun-2024

Dynamically adding and removing form fields using JavaScript involves manipulating the DOM to create and delete elements. This can be useful for forms that require a variable number of input fields, such as adding multiple addresses or phone numbers. 

Below is a step-by-step guide on how to achieve this.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Form Fields</title>
    <style>
        .field-container {
            margin-bottom: 10px;
        }
        .remove-button {
            margin-left: 10px;
            color: red;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <form id="dynamicForm">
        <div id="fieldContainer"></div>
        <button type="button" id="addButton">Add Field</button>
        <button type="submit">Submit</button>
    </form>

    <script src="dynamicFields.js"></script>
</body>
</html>

JavaScript for Dynamic Fields (dynamicFields.js)

document.addEventListener('DOMContentLoaded', function() {
    const fieldContainer = document.getElementById('fieldContainer');
    const addButton = document.getElementById('addButton');

    addButton.addEventListener('click', function() {
        addField();
    });

    function addField() {
        // Create a new div to hold the input and remove button
        const div = document.createElement('div');
        div.classList.add('field-container');

        // Create the input field
        const input = document.createElement('input');
        input.type = 'text';
        input.name = 'dynamicField[]';
        input.placeholder = 'Enter value';

        // Create the remove button
        const removeButton = document.createElement('span');
        removeButton.classList.add('remove-button');
        removeButton.textContent = 'Remove';
        removeButton.addEventListener('click', function() {
            removeField(div);
        });

        // Append the input and remove button to the div
        div.appendChild(input);
        div.appendChild(removeButton);

        // Append the div to the field container
        fieldContainer.appendChild(div);
    }

    function removeField(div) {
        fieldContainer.removeChild(div);
    }
});

Explanation

HTML Structure:

  • The form (#dynamicForm) contains a div (#fieldContainer) where new input fields will be added.
  • A button (#addButton) is provided to trigger the addition of new input fields.
  • A submit button is included to allow form submission.

CSS Styles (optional):

  • Styles are added to format the field container and remove the button for better presentation.

JavaScript for Dynamic Fields:

The JavaScript code is executed when the DOM content is loaded.

References to the field container (#fieldContainer) and the add button (#addButton) are obtained using getElementById.

An event listener is added to the add button to handle the click event, calling the addField function.

addField Function:

  • Creates a new div element with the class field-container.
  • Creates an input element with type text, a name attribute, and a placeholder.
  • Creates a span element with the class remove-button and the text 'Remove'. An event listener is added to the remove button to handle the click event, calling the removeField function.
  • Appends the input field and remove the button to the new div.
  • Appends the new div to the field container.

removeField Function:

  • Removes the specified div (containing the input field and remove button) from the field container.

Benefits

  • Flexibility: Allows users to dynamically add or remove input fields as needed.
  • Improved User Experience: Provides a more interactive and customizable form experience.
  • Simplicity: Easy to implement and manage with JavaScript.

 

Read Also :

What is the difference between null and undefined in JavaScript?

What is JavaScript, and how is it different from Java?


Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By